package com.itmake.sample.tenant.mycat;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 租户网络拦截器
 *
 * @author Amjacks
 * @since 2023/08/10
 */
@Component
public class TenantWebInterceptor implements HandlerInterceptor {

    @Value("#{${config.tenant}}")
    private Map<String, String> tenantMap;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 赋予租户
        String serverName = request.getServerName();
        for (String s : tenantMap.keySet()) {
            if (serverName.contains(s)) {
                TenantService.setTenantId(tenantMap.get(s));
            }
        }
        return Boolean.TRUE;
    }
}
